import java.io.*;
import java.net.*;

public class MyUdpClient {
    public static void main(String[] args) {
        String serverAddress = "127.0.0.1"; // 替换为服务端的IP地址
        int port = 6666; // 服务端端口

        try (DatagramSocket clientSocket = new DatagramSocket()) {
            byte[] sendData = "Time request".getBytes();
            byte[] receiveData = new byte[1024];

            InetAddress IPAddress = InetAddress.getByName(serverAddress);

            // 发送请求给服务端
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
            clientSocket.send(sendPacket);

            // 接收服务端返回的时间
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            clientSocket.receive(receivePacket);

            // 打印服务端返回的时间
            String received = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Time from server: " + received);

        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + serverAddress);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " + serverAddress);
            System.exit(1);
        }
    }
}